// 为数组添加随机元素函数
Array.prototype.randomItem = function () {
    return this[Math.floor(Math.random() * this.length)];
}

// 全局变量
const BookmarkTabConstant = {
    capacity: 8 * 4,
    bgUrl: "",
    bookmarkArr: [],
    sentenceInfo: {}
}

// 创建新标签页
const createNewTab = (url) => {
    const options = { url: url };
    // return () => chrome.tabs.create(options);
    return () => chrome.tabs.update(options);
}

/*
    <div class="bookmark">
      <div class="img"><img src="images/koala_icon_128.png"></div>
      <div class="text">百度一下，你就知道</div>
    </div>
 */
// 生成单个书签 DOM 对象
const createBookmarkDom = (bookmark) => {
    // 创建一个外层 div
    let container = document.createElement("div");
    // 为外层 div 创建 class
    let attr = document.createAttribute("class");
    attr.nodeValue = "bookmark";
    container.setAttributeNode(attr);
    // 给外层 div 添加点击事件
    container.addEventListener('click', createNewTab(bookmark.url));
    // 创建图片 div
    let imgDiv = document.createElement("div");
    attr = document.createAttribute("class");
    attr.nodeValue = "img";
    imgDiv.setAttributeNode(attr);
    // 获取网页 favicon 地址
    let arr = bookmark.url.split("/");
    let faviconUrl = arr[0] + "//" + arr[2] + "/favicon.ico";
    fetch(faviconUrl).then(res => {
        const contentType = res.headers.get('content-type');
        const contentLength = res.headers.get('content-length');
        // 1. 判断请求是否成功 
        // 2. 判断响应头的 content-length 字段是否大于0 
        // 3. 判断响应头的 content-type 字段是否存在
        // 4. 判断响应头的 content-type 字段是否以 `image/` 字符开头
        if (res.ok && contentLength > 0 && contentType && contentType.startsWith('image/')) {
            // 创建图片标签
            let img = document.createElement("img");
            attr = document.createAttribute("src");
            attr.nodeValue = faviconUrl;
            img.setAttributeNode(attr);
            imgDiv.appendChild(img);
        } else {
            return Promise.reject(res);
        }
    }).catch(err => {
        // console.log(err);
        // 创建用于替换 img 标签的 div，如果 favicon.ico 加载不出来的话，就用这个 div 替换
        let nameDiv = document.createElement("div");
        attr = document.createAttribute("class");
        attr.nodeValue = "name-box";
        nameDiv.setAttributeNode(attr);
        nameDiv.innerText = bookmark.title[0];
        nameDiv.style.backgroundColor = randomColor();
        imgDiv.appendChild(nameDiv);
    });
    // 创建文字 div
    let textDiv = document.createElement("div");
    attr = document.createAttribute("class");
    attr.nodeValue = "text";
    textDiv.setAttributeNode(attr);
    textDiv.innerHTML = bookmark.title;
    // 添加 children 结点
    container.appendChild(imgDiv);
    container.appendChild(textDiv);
    return container;
}

// 书签类
class Bookmark {
    constructor(category, title, url) {
        this.category = category;
        this.title = title;
        this.url = url;
    }
}


// 找到所有书签，放入书签对象数组中
const findBookmark = (results, targetArr) => {
    const children = results.children;
    if (!children) return;
    for (let item of children) {
        if (item.url) {
            let bookmark = new Bookmark(results.title, item.title, item.url);
            targetArr.push(bookmark);
        }
        findBookmark(item, targetArr);
    }
}


// 初始化壁纸
const initWallPaper = () => {
    const bg = chrome.extension.getBackgroundPage();
    let bgImg = document.getElementsByClassName("bg-img")[0];
    if (bg.getConfig) {
        bgImg.src = bg.getConfig().bgImage.src;
        BookmarkTabConstant.bgUrl = bgImg.src;
        bg.refreshWallPaper();
    } else {
        // 第一次加载，background.js 还未加载
        bgImg.src = 'https://api.66mz8.com/api/rand.acg.php?type=风景&format=jpg';
    }
}

// 初始化句子，来源：一言
const initSentence = () => {
    const url = 'https://v1.hitokoto.cn/';
    fetch(url).then(res => res.json())
        .then(res => {
            BookmarkTabConstant.sentenceInfo = res;
            const sentenceDiv = document.getElementById("sentence");
            sentenceDiv.children[0].innerHTML = `「 ${res.hitokoto} 」`;
            sentenceDiv.children[1].innerHTML = `—— ${res.from_who || res.from || res.creator}`;
        });
}


// 生成书签容器 DOM 对象
const createBookmarkContainerDom = (bookmarkArr) => {
    const capacity = BookmarkTabConstant.capacity;
    const len = bookmarkArr.length;
    const count = Math.ceil(len / capacity);
    let liArr = [];
    for (let i = 0; i < count; i++) {
        const li = document.createElement("li");
        for (let j = 0; j < capacity; j++) {
            if (bookmarkArr[i * capacity + j]) {
                let child = createBookmarkDom(bookmarkArr[i * capacity + j]);
                li.appendChild(child);
            } else {
                break;
            }
        }
        li.style.display = "none";
        liArr.push(li);
    }
    liArr[0].style.display = "grid";
    return liArr;
}

// 初始化下载按钮
const initDownloadIcon = () => {
    const downloadIcon = document.getElementsByClassName("download-icon")[0];
    downloadIcon.addEventListener("click", function (e) {
        const tagA = document.createElement("a");
        tagA.href = BookmarkTabConstant.bgUrl;
        tagA.download = "download";
        tagA.click();
        tagA.remove();
    });
};

// 当书签特别多的时候，切换 Tab
const changeTab = (function () {
    let startIndex = 0;
    return function (containers) {
        for (let index = 0; index < containers.length; index++) {
            if (startIndex === index) {
                containers[index].style.display = "grid";
            } else {
                containers[index].style.display = "none";
            }
        }
        startIndex = (startIndex + 1) % containers.length;
    }
})()

// 初始化
const initPage = () => {
    initWallPaper();
    initDownloadIcon();
    initSentence();
    let container = document.getElementById("container");
    chrome.bookmarks.getTree((res) => {
        findBookmark(res[0], BookmarkTabConstant.bookmarkArr);
        chrome.browserAction.setBadgeText({ text: BookmarkTabConstant.bookmarkArr.length.toString() });
        chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });
        const liArr = createBookmarkContainerDom(BookmarkTabConstant.bookmarkArr);
        for (let li of liArr) {
            container.appendChild(li);
        }
        // 鼠标滚动时间的监听
        window.onmousewheel = (event) => {
            console.log(event.wheelDelta);
            console.log(event);
            if (event.wheelDelta < 0) {
                // 向下滚
                changeTab(liArr);
            } else {
                // 向上滚
                changeTab(liArr);
            }
        }
    });
}

initPage();

/***************** 测试方法 *********************/
// 生成足够多的书签
const generateBookmarks = () => {
    let bookmarkArr = [];
    for (let i = 1; i <= 32; i++) {
        bookmarkArr.push(new Bookmark("搜索类网站", "百度", "http://www.baidu.com/"))
    }
    for (let i = 1; i <= 32; i++) {
        bookmarkArr.push(new Bookmark("搜索类网站", "淘宝", "http://www.taobao.com/"))
    }
    for (let i = 1; i <= 20; i++) {
        bookmarkArr.push(new Bookmark("搜索类网站", "网易云音乐", "https://music.163.com/"))
    }
    return bookmarkArr;
}